package org.anderground.editor.gui;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.Observable;
import java.util.Observer;

import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.UIManager;

import org.anderground.editor.gui.menubar.EditorMenuBar;
import org.anderground.editor.gui.menubar.SaveMapMenuItem;
import org.anderground.editor.gui.toolbar.EditorToolBar;
import org.anderground.editor.model.EditorModel;

@SuppressWarnings("serial")
public class MainWindow extends JFrame {

	private EditorPanel mainPanel;

	public static boolean modelChangedAfterLastSave = false;

	public MainWindow() {
		super("AndroidMetro editor");
		try {
			UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
		} catch (Exception e) {
		}
		this.setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
		addWindowListener(new WindowAdapter() {

			@Override
			public void windowClosing(WindowEvent arg0) {
				onClose();

			}

		});

		this.mainPanel = (new EditorPanel(this));
		this.getContentPane().add(getMainPanel());
		this.getContentPane().add(new EditorToolBar(this), BorderLayout.NORTH);
		this.setJMenuBar(new EditorMenuBar(this));
		this.pack();
		EditorModel.getInstance().addObserver(new Observer() {
			@Override
			public void update(Observable o, Object arg) {
				modelChangedAfterLastSave = true;
			}
		});
		mainPanel.getFirstView().afterPanelInit();
		mainPanel.getSecondView().afterPanelInit();

	}

	public void onClose() {
		int result = askForSave("Do you want to quit without saving?", this);
		if (result == JOptionPane.YES_OPTION
				|| result == JOptionPane.DEFAULT_OPTION) {
			System.exit(0);
		}
	}

	public EditorPanel getMainPanel() {
		return mainPanel;
	}

	public static int askForSave(String message, Component parent) {
		if (modelChangedAfterLastSave) {
			int dialogResault = JOptionPane.showConfirmDialog(parent, message,
					"Exit without save?", JOptionPane.YES_NO_CANCEL_OPTION);
			if (dialogResault == JOptionPane.NO_OPTION) {
				SaveMapMenuItem.showSaveFileDialog(parent);
				modelChangedAfterLastSave = false;
			}
			return dialogResault;

		}
		return JOptionPane.DEFAULT_OPTION;
	}

}
